{% extends "前端/template.html" %}

{% block title %}
登录 | 注册 - 锐眼识别
{% endblock %}

{% block css %}
<style>
    .authentication-wrapper {
        display: flex;
        flex-basis: 100%;
        min-height: 100vh;
        width: 100%;
    }
    
    .authentication-wrapper .authentication-inner {
        width: 100%;
    }
    
    .authentication-wrapper.authentication-basic {
        align-items: center;
        justify-content: center;
        overflow: hidden;
    }
    
    .auth-cover-bg {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: linear-gradient(45deg, rgba(105, 108, 255, 0.1), rgba(105, 108, 255, 0.3));
        z-index: -1;
    }
    
    .authentication-basic .authentication-inner {
        max-width: 400px;
        position: relative;
    }
    
    .card-auth {
        box-shadow: 0 2px 6px 0 rgba(67, 89, 113, 0.12);
    }
    
    .form-auth .form-floating {
        margin-bottom: 1rem;
    }
    
    .form-auth .form-floating input {
        height: calc(3rem + 2px);
        padding: 1rem 0.875rem;
    }
    
    .form-auth .form-floating label {
        padding: 1rem 0.875rem;
    }

    .auth-footer-text {
        text-align: center;
        font-size: 0.875rem;
        color: #697a8d;
    }
</style>
{% endblock %}

{% block content %}
<div class="authentication-wrapper authentication-basic">
    <div class="auth-cover-bg"></div>
    <div class="authentication-inner py-4">
        <div class="card card-auth">
            <div class="card-body">
                <!-- Logo -->
                <div class="app-brand justify-content-center mb-4 mt-2">
                    <span class="app-brand-text demo text-primary fw-bold">锐眼识别</span>
                </div>
                
                <!-- 切换标签 -->
                <ul class="nav nav-pills mb-4 nav-justified" role="tablist">
                    <li class="nav-item">
                        <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#login-tab" type="button" role="tab">登录</button>
                    </li>
                    <li class="nav-item">
                        <button class="nav-link" data-bs-toggle="tab" data-bs-target="#register-tab" type="button" role="tab">注册</button>
                    </li>
                </ul>
                
                <!-- 表单内容 -->
                <div class="tab-content">
                    <!-- 登录表单 -->
                    <div class="tab-pane fade show active" id="login-tab" role="tabpanel">
                        <form class="form-auth" id="loginForm">
                            <div class="form-floating">
                                <input type="text" class="form-control" id="login-username" placeholder="用户名/邮箱" required>
                                <label for="login-username">用户名/邮箱</label>
                            </div>
                            <div class="form-floating">
                                <input type="password" class="form-control" id="login-password" placeholder="密码" required>
                                <label for="login-password">密码</label>
                            </div>
                            <div class="mb-3 d-flex justify-content-between">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="remember-me">
                                    <label class="form-check-label" for="remember-me">记住我</label>
                                </div>
                                <a href="javascript:void(0);" class="text-primary">忘记密码？</a>
                            </div>
                            <button class="btn btn-primary d-grid w-100 mb-3" type="submit">登录</button>
                        </form>
                    </div>
                    
                    <!-- 注册表单 -->
                    <div class="tab-pane fade" id="register-tab" role="tabpanel">
                        <form class="form-auth" id="registerForm">
                            <div class="form-floating">
                                <input type="text" class="form-control" id="register-username" placeholder="用户名" required>
                                <label for="register-username">用户名</label>
                            </div>
                            <div class="form-floating">
                                <input type="email" class="form-control" id="register-email" placeholder="邮箱" required>
                                <label for="register-email">邮箱</label>
                            </div>
                            <div class="form-floating">
                                <input type="password" class="form-control" id="register-password" placeholder="密码" required>
                                <label for="register-password">密码</label>
                            </div>
                            <div class="form-floating">
                                <input type="password" class="form-control" id="register-confirm-password" placeholder="确认密码" required>
                                <label for="register-confirm-password">确认密码</label>
                            </div>
                            <div class="mb-3">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="terms-conditions" required>
                                    <label class="form-check-label" for="terms-conditions">
                                        我同意 <a href="javascript:void(0);" class="text-primary">服务条款</a> 和 <a href="javascript:void(0);" class="text-primary">隐私政策</a>
                                    </label>
                                </div>
                            </div>
                            <button class="btn btn-primary d-grid w-100 mb-3" type="submit">注册</button>
                        </form>
                    </div>
                </div>
                
                <!-- 社交登录 -->
                <!-- <div class="divider my-4">
                    <div class="divider-text">或者使用</div>
                </div>
                
                <div class="d-flex justify-content-center gap-2">
                    <button type="button" class="btn btn-icon btn-outline-primary">
                        <i class="bx bxl-google"></i>
                    </button>
                    <button type="button" class="btn btn-icon btn-outline-primary">
                        <i class="bx bxl-github"></i>
                    </button>
                    <button type="button" class="btn btn-icon btn-outline-primary">
                        <i class="bx bxl-twitter"></i>
                    </button>
                </div> -->
            </div>
        </div>
        
        <!-- 页脚文本 -->
        <div class="auth-footer-text mt-4">
            <p>
                © <script>document.write(new Date().getFullYear());</script> 锐眼识别. 保留所有权利
            </p>
        </div>
    </div>
</div>
{% endblock %}

{% block js %}
<script>
    // 表单验证函数
    function validatePassword(password) {
        // 密码长度6-12位
        if (password.length < 6 || password.length > 12) {
            return '密码长度必须在6-12位之间';
        }
        // 密码只能包含字母、数字、@符号和下划线
        if (!/^[a-zA-Z0-9@_]+$/.test(password)) {
            return '密码只能包含字母、数字、@符号和下划线';
        }
        return null;
    }

    function validateEmail(email) {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) {
            return '请输入有效的邮箱地址';
        }
        return null;
    }

    function validateUsername(username) {
        if (username.length < 2) {
            return '用户名长度不能小于2位';
        }
        return null;
    }

document.addEventListener('DOMContentLoaded', function() {
    const loginForm = document.getElementById('loginForm');
    const registerForm = document.getElementById('registerForm');
    
    // 登录表单提交
    loginForm.addEventListener('submit', async function(e) {
        e.preventDefault();
        
        // 获取表单数据
        const username = document.getElementById('login-username').value;
        const password = document.getElementById('login-password').value;
        const rememberMe = document.getElementById('remember-me').checked;
        
        // 显示加载中
        showLoading('登录中...');
        
        try {
            // 构造表单数据
            const formData = new URLSearchParams();
            // 判断输入是邮箱还是用户名
            if (username.includes('@')) {
                formData.append('email', username);
            } else {
                formData.append('username', username);
            }
            formData.append('password', password);
            // 发送登录请求
            const response = await axios.post('/api/users/login/', formData);
            
            const result = response.data;
            
            if (result.code === 200) {
                // 登录成功
                // 如果选择了记住我，可以将用户信息存储在localStorage，否则存在sessionStorage
                const storage = rememberMe ? localStorage : sessionStorage;
                storage.setItem('userInfo', JSON.stringify(result.data));
                
                // 显示成功提示
                hideLoading();
                showToast('登录成功，欢迎回来，' + result.data.username, 'success');
                
                // 延迟跳转到首页
                setTimeout(() => {
                    window.location.href = '/web/home/index/';
                }, 1000);
            } else {
                // 登录失败
                hideLoading();
                showToast(result.data || result.message, 'error');
            }
        } catch (error) {
            console.error('登录请求失败:', error);
            hideLoading();
            showToast('网络错误，请稍后重试', 'error');
        }
    });

    // 注册表单提交
    registerForm.addEventListener('submit', async function(e) {
        e.preventDefault();
        
        // 获取表单数据
        const username = document.getElementById('register-username').value.trim();
        const email = document.getElementById('register-email').value.trim();
        const password = document.getElementById('register-password').value;
        const confirmPassword = document.getElementById('register-confirm-password').value;
        const termsAccepted = document.getElementById('terms-conditions').checked;
        
        // 表单验证
        if (!termsAccepted) {
            showToast('请阅读并同意服务条款和隐私政策', 'warning');
            return;
        }

        // 验证用户名
        const usernameError = validateUsername(username);
        if (usernameError) {
            showToast(usernameError, 'warning');
            return;
        }

        // 验证邮箱
        const emailError = validateEmail(email);
        if (emailError) {
            showToast(emailError, 'warning');
            return;
        }

        // 验证密码
        const passwordError = validatePassword(password);
        if (passwordError) {
            showToast(passwordError, 'warning');
            return;
        }

        // 确认密码
        if (password !== confirmPassword) {
            showToast('两次输入的密码不一致', 'warning');
            return;
        }
        
        // 显示加载中
        showLoading('注册中...');
        
        try {
            // 构造表单数据
            const formData = new URLSearchParams();
            formData.append('username', username);
            formData.append('email', email);
            formData.append('password', password);
            
            // 发送注册请求
            const response = await axios.post('/api/users/register/', formData);
            const result = response.data;
            
            if (result.code === 200) {
                // 注册成功
                hideLoading();
                showToast('注册成功！', 'success');
                
                // 存储用户信息
                sessionStorage.setItem('userInfo', JSON.stringify(result.data));
                
                // 延迟跳转到首页
                setTimeout(() => {
                    window.location.href = '/web/home/index/';
                }, 1000);
            } else {
                // 注册失败
                hideLoading();
                
                // 处理错误信息
                if (result.data) {
                    if (typeof result.data === 'string') {
                        // 处理密码验证失败的情况
                        showToast(result.data, 'error');
                    } else {
                        // 处理字段验证错误（如邮箱已存在）
                        for (const field in result.data) {
                            if (Array.isArray(result.data[field])) {
                                // 处理邮箱已存在等字段错误
                                const error = result.data[field][0];
                                showToast(error.message || `${field}验证失败`, 'error');
                            } else {
                                // 处理其他字段错误
                                showToast(result.data[field], 'error');
                            }
                            break; // 只显示第一个错误
                        }
                    }
                } else {
                    showToast(result.message || '注册失败', 'error');
                }
            }
        } catch (error) {
            console.error('注册请求失败:', error);
            hideLoading();
            showToast('网络错误，请稍后重试', 'error');
        }
    });
});
</script>
{% endblock %}

{% block nav_left %}{% endblock %}
{% block NavBar %}{% endblock %}
{% block footer %}{% endblock %}